import { requestInterceptor, responseInterceptor, errorInterceptor } from './interceptor'
import { useUserStore } from '@/store/user'
import { showLoading, hideLoading } from './loading'
import config from '@/config.js';

const BASE_URL = config.baseURL; // 根据实际后端端口调整

function showGlobalLoading() {
  showLoading({ title: '加载中...' });
}
function hideGlobalLoading() {
  hideLoading();
}

function refreshToken() {
  return new Promise((resolve, reject) => {
    const userStore = useUserStore();
    uni.request({
      url: BASE_URL + '/wechat/refreshToken',
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      data: {
        refreshToken: userStore.refreshToken
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === '0') {
          const { accessToken, refreshToken } = res.data.data;
          userStore.updateToken({ accessToken, refreshToken });
          resolve({ accessToken, refreshToken });
        } else {
          reject(res.data);
        }
      },
      fail: reject
    });
  });
}

/**
 * 执行单次请求（不包含token刷新逻辑）
 * @param {Object} options - 请求配置
 * @returns {Promise}
 */
function makeRequest(options) {
  return new Promise((resolve, reject) => {
    const userStore = useUserStore();
    const config = requestInterceptor(options);
    
    if (!config.header) config.header = {};
    if (userStore.accessToken) {
      config.header['token'] = userStore.accessToken;
    }
    
    const fullUrl = config.url && config.url.startsWith('http') ? config.url : `${BASE_URL}${config.url || options.url}`;
    
    // 添加10秒超时
    const timeoutId = setTimeout(() => {
      reject(new Error('请求超时'));
    }, 10000);
    
    uni.request({
      url: fullUrl,
      method: config.method || 'GET',
      data: config.data || config.params || {},
      header: config.header,
      success: (res) => {
        clearTimeout(timeoutId);
        try {
          const data = responseInterceptor(res);
          resolve(data);
        } catch (error) {
          reject(error);
        }
      },
      fail: (err) => {
        clearTimeout(timeoutId);
        errorInterceptor(err);
        reject(err);
      }
    });
  });
}

/**
 * 处理token刷新和重试的请求方法
 * @param {Object} options - 请求配置
 * @returns {Promise}
 */
async function makeRequestWithRetry(options) {
  try {
    return await makeRequest(options);
  } catch (error) {
    // 检查是否是token失效错误
    if (error && error.data && error.data.code === '8001') {
      try {
        // 刷新token
        await refreshToken();
        // 重试请求
        return await makeRequest(options);
      } catch (refreshError) {
        // token刷新失败，跳转登录
        const userStore = useUserStore();
        userStore.logout();
        uni.redirectTo({ url: '/pages/login/index' });
        throw refreshError;
      }
    }
    throw error;
  }
}

/**
 * 统一请求方法，集成全局loading和自动刷新token（双token机制）
 * @param {Object} options - 请求配置
 * @returns {Promise}
 */
export default async function request(options) {
  showGlobalLoading();
  
  try {
    const result = await makeRequestWithRetry(options);
    return result;
  } catch (error) {
    throw error;
  } finally {
    hideGlobalLoading();
  }
}